package hot;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lakersUp
 * @Classname   电话号码的组合
 * @Description     回溯
 * @Date 2022/3/8 16:16
 * @Version 1.0
 */
public class Hot17letterCombinations {
    List<String> list=new ArrayList<>();
    public List<String> letterCombinations(String digits) {
        if(digits==null || digits.length()==0){
            return list;
        }
        Map<Character, String> map = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backTrack(digits,new StringBuffer(),0,map);
        return list;
    }

    private void backTrack(String digits, StringBuffer sb, int index, Map<Character, String> map) {
        if(index==digits.length()){
            list.add(sb.toString());
            return;
        }
        char c = digits.charAt(index);
        String s = map.get(c);
        for(int i=0;i<s.length();i++){
            sb.append(s.charAt(i));
            backTrack(digits, sb, index+1, map);
            //sb的长度最大为2, 所以删除的是index而不是i
            sb.deleteCharAt(index);
        }
    }
}
